package cn.com.connext.scrm.web.rest;

import cn.com.connext.scrm.client.MemberClient;
import cn.com.connext.scrm.domain.master.Activity;
import cn.com.connext.scrm.domain.master.AwardRecord;
import cn.com.connext.scrm.service.ActivityService;
import cn.com.connext.scrm.service.dto.*;
import cn.com.connext.scrm.service.mapper.ActivitiesService;
import cn.com.connext.scrm.web.rest.errors.MyErrorCode;
import cn.com.connext.scrm.web.rest.req.*;
import cn.com.connext.scrm.web.rest.resp.QueryActivitiesResp;
import cn.com.connext.scrm.web.rest.resp.QueryNowAndPostActivitiesResp;
import cn.com.connext.scrm.web.rest.vm.*;
import com.alibaba.fastjson.JSON;
import com.codahale.metrics.annotation.Timed;
import com.connext.common.exception.ServiceException;
import com.connext.common.web.rest.BaseResource;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeoutException;

/**
 * Created by WangZhan on 2019/01/24.
 */
@RestController
@RequestMapping("/api/activity")
public class ActivityResource extends BaseResource {
    private final Logger log = LoggerFactory.getLogger(ActivityResource.class);

    @Autowired
    private ActivityService activityService;

    @Autowired
    private MemberClient memberClient;

    @Autowired
    private ActivitiesService activitiesService;

    public ActivityResource() throws TimeoutException {
        super("Activity");
    }

    /**
     * 创建威士忌之星活动
     */
    @PostMapping("/answer-create")
    @ApiOperation(value = "创建威士忌之星活动", tags = {"威士忌之星活动列表"}, notes = "创建威士忌之星活动")
    public ResponseEntity<Boolean> create(@RequestBody ActivityCreateReq req) {
        log.info("创建威士忌之星活动，入参req : {}", JSON.toJSONString(req));
        if (req == null) {
            throw new ServiceException(MyErrorCode.ERROR_INPUT);
        }
        return activitiesService.create(req);
    }

    /**
     * 更新威士忌之星问答活动
     */
    @PostMapping("/answer-update")
    @ApiOperation(value = "更新威士忌之星问答活动", tags = {"问答活动列表"}, notes = "更新问答活动")
    public ResponseEntity<Boolean> update(@RequestBody ActivityUpdateReq req) {
        log.info("更新威士忌之星问答活动，入参req : {}", JSON.toJSONString(req));
        if (req == null) {
            throw new ServiceException(MyErrorCode.ERROR_INPUT);
        }
        return activitiesService.update(req);
    }

    /**
     * 审核威士忌之星活动
     */
    @PostMapping("/answer-audit")
    @ApiOperation(value = "审核威尼斯之星活动", tags = {"问答活动列表"}, notes = "审核威士忌之星活动")
    public ResponseEntity audit(@RequestBody ActivityAuditReq req) {
        log.info("审核威士忌之星活动，入参req : {}", JSON.toJSONString(req));
        if (null == req) {
            throw new ServiceException(MyErrorCode.ERROR_INPUT);
        }
        return activitiesService.audit(req);
    }

    /**
     * 威士忌之星活动列表
     */
    @PostMapping("/answer-query")
    @ApiOperation(value = "威士忌之星活动列表", tags = {"威士忌之星活动列表"}, notes = "威士忌之星活动列表")
    public ResponseEntity<Page<QueryActivitiesResp>> queryActivities(@RequestBody ActivityQueryReq req) {
        log.info("威士忌之星活动列表，入参req : {}", JSON.toJSONString(req));
        return activitiesService.queryActivities(req);
    }

    /**
     * 当前威士忌之星活动
     */
    @PostMapping("/answer-now-activities")
    @ApiOperation(value = "当前威士忌之星活动", tags = {"当前威士忌之星活动"}, notes = "当前威士忌之星活动")
    public ResponseEntity<QueryNowAndPostActivitiesResp> queryAnswerNowActivities() {
        log.info("查询当前威士忌之星活动");
        return activitiesService.queryAnswerNowActivities();
    }

    /**
     * 当前参与威士忌之星活动活动帖子
     */
    @PostMapping("/answer-now-notes")
    @ApiOperation(value = "当前参与威士忌之星活动活动帖子", tags = {"问答活动列表"}, notes = "当前参与威士忌之星活动活动帖子")
    public ResponseEntity<Page> queryAnswerNowNotes(@RequestBody PageBaseReq req) {
        log.info("查询当前活动帖子");
        return activitiesService.queryAnswerNowNotes(req);
    }

    /**
     * 往期威士忌之星活动
     */
    @PostMapping("/answer-post-activities")
    @ApiOperation(value = "查询问答往期活动", tags = {"问答活动列表"}, notes = "查询问答往期活动")
    public ResponseEntity<List<QueryNowAndPostActivitiesResp>> queryAnswerPostActivities() {
        log.info("查询往期威士忌之星活动");
        return activitiesService.queryAnswerPostActivities();
    }

    /**
     * 往期威士忌之星活动详情  小程序
     */
    @PostMapping("/answer-post-detail")
    @ApiOperation(value = "查询问答往期活动", tags = {"问答活动列表"}, notes = "查询问答往期活动")
    public ResponseEntity<QueryNowAndPostActivitiesResp> queryAnswerPostActivitiesDetail(@RequestBody QueryAnswerPostNotesReq req) {
        log.info("查询往期威士忌之星活动");
        if (StringUtils.isEmpty(req.getActId())) {
            throw new ServiceException(MyErrorCode.ERROR_INPUT);
        }
        return activitiesService.queryAnswerPostActivitiesDetail(req.getActId());
    }

    /**
     * 往期活动帖子
     */
    @PostMapping("/answer-post-notes")
    @ApiOperation(value = "询问答往期活动帖子", tags = {"问答活动列表"}, notes = "询问答往期活动帖子")
    public ResponseEntity<Page> queryAnswerPostNotes(@RequestBody QueryAnswerPostNotesReq req) {
        log.info("询问答往期活动帖子");
        if (StringUtils.isEmpty(req.getActId())) {
            throw new ServiceException(MyErrorCode.ERROR_INPUT);
        }
        return activitiesService.queryAnswerPostNotes(req);
    }

    /**
     * 活动启用
     */
    @PostMapping("/answer-enable")
    @Timed
    @ApiOperation(value = "活动启用", tags = {"活动管理"}, notes = "活动启用")
    public ResponseEntity answerenable(@RequestBody QueryIdVM req) {
        log.info("活动启用入参req={}", JSON.toJSONString(req));
        JsonResult result = new JsonResult();
        try {
            result = activitiesService.answerenable(req);
            return entityResponse(result);
        } catch (Exception e) {
            log.error("启用失败:{}", e);
            result.setState(1);
            result.setMessage("启用失败");
            return entityResponse(result);
        }
    }

    /**
     * 威士忌之星活动详情
     */
    @PostMapping("/answer-detail")
    @ApiOperation(value = "威士忌之星活动详情", tags = {"问答活动详情"}, notes = "威士忌之星活动详情")
    public ResponseEntity<QueryActivitiesResp> detail(@RequestBody ActivityDetailReq req) {
        log.info("威士忌之星活动详情，入参req : {}", JSON.toJSONString(req));
        return activitiesService.detail(req);
    }

    @GetMapping("/getCurrentActivities")
    @Timed
    @ApiOperation(value = "获取当前启用活动", tags = {"活动管理"}, notes = "获取当前启用活动")
    public ResponseEntity getCurrentActivities() {

        List<Activity> activities = activityService.getCurrentActivities();
        return entityResponse(activities);
    }

    @Deprecated
    @GetMapping("/getAwardRecordByUnionId/{unionId}")
    @Timed
    @ApiOperation(value = "获取获奖记录", tags = {"活动管理"}, notes = "根据unionId获取获奖记录")
    public ResponseEntity getAwardRecordByUnionId(@PathVariable(value = "unionId") String unionId) {
        AwardRecordDTO dto = activityService.getAwardRecordByUnionId(unionId);
        if (dto != null) {
            return entityResponse(dto);
        }
        return entityResponse("无获奖记录");
    }

    /**
     * 删除活动
     * @param vm
     * @return
     */
    @PostMapping("/delete")
    @Timed
    @ApiOperation(value = "活动删除", tags = {"活动管理"}, notes = "活动删除")
    public ResponseEntity delete(@RequestBody QueryIdVM vm) {
        JsonResult result = new JsonResult();
        try {
            activityService.deleteById(vm.getId());
            result.setMessage("删除成功");
            result.setState(0);
            return entityResponse(result);
        } catch (Exception e) {
            log.error("删除失败:{}", e);
            result.setMessage("删除失败");
            result.setState(1);
            return entityResponse(result);
        }
    }

    /**
     * 删除活动
     * @param vm
     * @return
     */
    @PostMapping("/draw/delete")
    @Timed
    @ApiOperation(value = "活动删除", tags = {"活动配置"}, notes = "活动删除")
    public ResponseEntity deleteDraw(@RequestBody QueryIdVM vm) {
        JsonResult result = new JsonResult();
        try {
            DrawActivityDTO dto = activityService.drawDetail(vm.getId());
            if(dto !=null){
                if(dto.getCanDelete() == 2){
                    result.setMessage("定制化活动不允许被删除");
                    result.setState(1);
                    return entityResponse(result);
                }
            }
            activityService.deleteDrawById(vm.getId());
            result.setMessage("删除成功");
            result.setState(0);
            return entityResponse(result);
        } catch (Exception e) {
            log.error("删除失败:{}", e);
            result.setMessage("删除失败");
            result.setState(1);
            return entityResponse(result);
        }
    }

    @PostMapping("/getAwardRecordByUnionId")
    @Timed
    @ApiOperation(value = "获取获奖记录", tags = {"活动管理"}, notes = "根据unionId获取获奖记录")
    public ResponseEntity getAwardRecordByUnionId(@RequestBody UnionIdVM vm) {
        AwardRecordDTO dto = activityService.getAwardRecordByUnionId(vm.getUnionId());
        if (dto != null) {
            return entityResponse(dto);
        }
        return entityResponse("无获奖记录");
    }

    @PostMapping("/submitExpressAddress")
    @Timed
    @ApiOperation(value = "提交奖品邮递地址", tags = {"活动管理"}, notes = "提交奖品邮递地址")
    public ResponseEntity submitExpressAddress(String awardRecordId, String expressAddress, String expressMobile, String addressee) {

        return entityResponse(activityService.submitExpressAddress(awardRecordId, expressAddress, expressMobile, addressee));
    }

    /**
     * 活动列表
     * @param vm
     * @return
     */
    @PostMapping("/list")
    @Timed
    @ApiOperation(value = "活动列表", tags = {"活动管理"}, notes = "活动列表")
    public ResponseEntity list(@RequestBody PageQueryVM vm) {
        try {
            Page<ActivityDTO> page = activityService.pageQuery(vm);
            return pagedResponse(page);
        } catch (Exception e) {
            log.error("查询失败:{}", e);
            return null;
        }
    }

    /**
     * 活动列表
     * @param vm
     * @return
     */
    @PostMapping("/draw/list")
    @Timed
    @ApiOperation(value = "活动列表", tags = {"活动配置"}, notes = "活动列表")
    public JsonResult drawList(@RequestBody QueryActivityVM vm) {
        JsonResult result = new JsonResult();

        try {
            Page<DrawActivityDTO> page = activityService.queryDrawList(vm);
            result.setData(page);
            result.setState(1);
            result.setMessage("查询成功");
            return result;
        } catch (Exception e) {
            log.error("查询失败:{}", e);
            return null;
        }
    }

    /**
     * 编辑活动
     * @param vm
     * @return
     */
    @PostMapping("/edit")
    @Timed
    @ApiOperation(value = "活动编辑", tags = {"活动管理"}, notes = "活动编辑")
    public ResponseEntity edit(@RequestBody ActivityVM vm) {
        JsonResult result = new JsonResult();
        try {
            ActivityDTO dto = activityService.edit(vm);
            result.setState(0);
            result.setMessage("编辑成功");
            result.setData(dto);
            return entityResponse(result);
        } catch (Exception e) {
            log.error("编辑失败:{}", e);
            result.setState(1);
            result.setMessage("编辑失败");
            return entityResponse(result);
        }
    }

    /**
     * 编辑活动
     * @param vm
     * @return
     */
    @PostMapping("/draw/edit")
    @Timed
    @ApiOperation(value = "活动编辑", tags = {"活动配置"}, notes = "活动编辑")
    public ResponseEntity editDrawActivity(@RequestBody DrawActivityVM vm) {
        JsonResult result = new JsonResult();
        try {
            if(StringUtils.isEmpty(vm.getCampaignID())){
                result.setState(-1);
                result.setMessage("参数campaignID不能为空!");
            }
            if(StringUtils.isEmpty(vm.getSource())){
                result.setState(-1);
                result.setMessage("参数source不能为空!");
            }
            if(StringUtils.isEmpty(vm.getSourceContent())){
                result.setState(-1);
                result.setMessage("参数sourceContent不能为空!!");
            }
            DrawActivityDTO dto = activityService.editDraw(vm);
            result.setState(0);
            result.setMessage("编辑成功");
            result.setData(dto);
            return entityResponse(result);
        } catch (Exception e) {
            log.error("编辑失败:{}", e);
            result.setState(1);
            result.setMessage("编辑失败");
            return entityResponse(result);
        }
    }

    /**
     * 开启活动
     * @param vm
     * @return
     */
    @PostMapping("/enable")
    @Timed
    @ApiOperation(value = "活动启用", tags = {"活动管理"}, notes = "活动启用")
    public ResponseEntity enable(@RequestBody QueryIdVM vm) {
        JsonResult result = new JsonResult();
        try {
            activityService.enable(vm.getId());
            result.setMessage("操作成功");
            result.setState(0);
            return entityResponse(result);
        } catch (Exception e) {
            log.error("启用失败:{}", e);
            result.setState(1);
            result.setMessage("启用失败");
            return entityResponse(result);
        }
    }

    /**
     * 开启活动
     * @param vm
     * @return
     */
    @PostMapping("/draw/enable")
    @Timed
    @ApiOperation(value = "活动启用", tags = {"活动配置"}, notes = "活动启用")
    public ResponseEntity drawEnable(@RequestBody QueryIdVM vm) {
        JsonResult result = new JsonResult();
        try {
            activityService.drawEnable(vm.getId());
            result.setMessage("操作成功");
            result.setState(0);
            return entityResponse(result);
        } catch (Exception e) {
            log.error("启用失败:{}", e);
            result.setState(1);
            result.setMessage("启用失败");
            return entityResponse(result);
        }
    }

    /**
     * 活动详情
     * @param vm
     * @return
     */
    @PostMapping("/detail")
    @Timed
    @ApiOperation(value = "活动详情", tags = {"活动管理"}, notes = "活动详情")
    public ResponseEntity detail(@RequestBody QueryIdVM vm) {
        JsonResult result = new JsonResult();
        try {
            ActivityDTO activityDTO = activityService.detail(vm.getId());
            result.setMessage("查询成功");
            result.setState(0);
            result.setData(activityDTO);
            return entityResponse(result);
        } catch (Exception e) {
            log.error("查询失败:{}", e);
            result.setState(1);
            result.setMessage("查询失败");
            return entityResponse(result);
        }
    }

    /**
     * 活动详情
     * @param vm
     * @return
     */
    @PostMapping("draw/detail")
    @Timed
    @ApiOperation(value = "活动详情", tags = {"活动配置"}, notes = "活动详情")
    public ResponseEntity drawDetail(@RequestBody QueryIdVM vm) {
        JsonResult result = new JsonResult();
        try {
            DrawActivityDTO activityDTO = activityService.drawDetail(vm.getId());
            result.setMessage("查询成功");
            result.setState(0);
            result.setData(activityDTO);
            return entityResponse(result);
        } catch (Exception e) {
            log.error("查询失败:{}", e);
            result.setState(1);
            result.setMessage("查询失败");
            return entityResponse(result);
        }
    }

    @PostMapping("/consumeCard")
    @Timed
    @ApiOperation(value = "核销", tags = {"活动管理"}, notes = "核销")
    public ResponseEntity consumeCard(@RequestBody ConsumeCardVM vm) {
        try {
            if (StringUtils.isNotEmpty(vm.getUnionId()) || !"null".equals(vm.getUnionId())) {
                AwardRecord record = activityService.consumeCard(vm.getUnionId(), vm.getCardId());
                if (record != null) {
                    return createSuccess("ok");
                }
                return null;
            } else {
                return null;
            }
        } catch (Exception e) {
            log.error("核销失败:{}", e);
            return null;
        }
    }

    @PostMapping("/close")
    @Timed
    @ApiOperation(value = "关闭", tags = {"活动管理"}, notes = "关闭")
    public ResponseEntity close(@RequestBody QueryIdVM vm) {
        try {
            if (vm == null) {
                throw new ServiceException(MyErrorCode.ERROR_ID_EMPTY);
            }
            activityService.closeCard(vm);
            return createSuccess("ok");
        } catch (Exception e) {
            log.error("关闭失败:{}", e);
            return null;
        }
    }

    @PostMapping("/getNoteByActivityId")
    @Timed
    @ApiOperation(value = "获取当前活动下的帖子", tags = {"活动管理"}, notes = "获取当前活动下的帖子")
    public ResponseEntity getNoteByActivityId(@RequestBody ActivityIdPageVM vm) {
        Page<NoteDTO> list = activityService.getNoteByActivityId(vm);
        return entityResponse(list);
    }

}
